import React from 'react'
import styles from './index.module.css'
import {Tag, Stepper, Toast} from 'antd-mobile'
import bgImg from '../../../assets/golive/pic_dt.png'
import Nav from '../../../components/nav'
import food2 from '../../../assets/products/food2.jpg'
import {withRouter, RouteComponentProps} from 'react-router-dom'
// import QueueAnim from 'rc-queue-anim';

import {connect} from "react-redux";
import request from "../../../utils/request";
import {Dispatch} from "redux";
import {buySku} from "../../../redux/reducers/order";

const Spec: React.FC<{
    skuTagList: skuTag[], productDetail: product | null, buyNum: number, selectedSku: selectedSku | null,
    selectedAttrIds: Record<number, number>, stepperChange: any, onSelect: any, onEnsure: any
}>
    = ({skuTagList, productDetail, buyNum, selectedSku, selectedAttrIds, stepperChange, onSelect, onEnsure}) => {
    return (
        <div className={styles.spec} key={1}>
            <img src={food2} alt="商品概述图片" style={{
                width: '100px',
                position: 'absolute',
                top: '-10px',
                left: '10px'
            }}/>
            <div style={{marginLeft: '120px'}}>
                <h3>{productDetail?.name}</h3>
                <b>¥{selectedSku ? selectedSku.price : productDetail?.price}</b>
                <span
                    style={{marginLeft: '6px'}}>库存 {selectedSku ? selectedSku.stock : productDetail?.totalStock}</span>
            </div>
            <div style={{
                marginTop: '30px'
            }}/>
            {
                skuTagList.map((item, inx) => {
                    let {skuAttrList} = item;
                    return (
                        <div key={inx}>
                            <div style={{margin: '6px 0 6px 6px',}}>{item.name}</div>
                            <div className={styles.property}>
                                {
                                    skuAttrList.map((attr, key) => {
                                        return (<Tag style={{marginLeft: '6px'}} key={key} onChange={(selected) => {
                                            onSelect(selected, attr);
                                        }} selected={selectedAttrIds[item.id] === attr.id}>{attr.name}</Tag>)
                                    })
                                }
                            </div>
                        </div>
                    );
                })
            }
            <div className={styles.buy}>
                <span style={{color: 'gray'}}>购买数量</span>
                <Stepper
                    showNumber
                    // @ts-ignore
                    style={{width: '120px', marginRight: '10px'}}
                    max={10} min={1}
                    value={buyNum}
                    onChange={stepperChange}
                />
            </div>

            <div style={{
                padding: '5px 10px',
                borderTop: '1px solid #F4F4F4'
            }}>
                <button
                    style={{
                        width: '100%',
                        border: 'none',
                        padding: '10px 5px',
                    }}
                    onClick={() => {
                        onEnsure();
                    }}>确定
                </button>
            </div>
        </div>
    );
};


interface Props extends RouteComponentProps<{ productId: string }> {
    dispatch: Dispatch
}

interface product {
    id: number,
    name: string,
    image: string
    price: number,
    sales: number,
    totalStock: number,
    freight: number,
}

interface skuAttr {
    id: number,
    name: string,
    skuTagId: number,
}

interface skuTag {
    id: number,
    name: string,
    skuAttrList: skuAttr[],
}

interface selectedSku {
    id: number,
    stock: number,
    price: number,
    skuFullName: string,
}

type popupStatus = 'addCart' | 'buyNow' | 'hidden';

interface States {
    selectedAttrIds: Record<number, number>,//{"tagId"=>"attrId"}
    selectedSku: selectedSku | null
    isCollect: boolean,
    productDetail: product | null,
    skuTagList: skuTag[],
    buyNum: number,
    popupStatus: popupStatus,
}


class Index extends React.Component<Props, States> {

    state: States = {
        selectedAttrIds: [],
        selectedSku: null,
        isCollect: false,
        productDetail: null,
        skuTagList: [],
        buyNum: 1,
        popupStatus: 'hidden'
    };

    stepperChange = (value: number) => {
        this.setState({
            buyNum: value
        });
    };
    onEnsure = () => {
        const {popupStatus, selectedSku, buyNum, productDetail} = this.state;
        const {history, match: {params: {productId}}, dispatch, location} = this.props;
        if (popupStatus === 'addCart') {
            this.addCart().then(() => {
                Toast.success('添加成功，在购物车等亲~', 1);
            });
            this.toggleSpec('hidden')
        }
        if (popupStatus === 'buyNow') {

            const buySkuList: buySku[] = [
                {
                    skuId: selectedSku!.id,
                    num: buyNum,
                    skuPrice: selectedSku!.price,
                    productName: productDetail!.name,
                    skuFullName: selectedSku!.skuFullName
                }
            ];
            dispatch({
                type: 'checkoutOrder',
                payload: buySkuList,
            });
            // dispatch({
            //     type: 'orderCheckoutBackUrlSet',
            //     payload: location.pathname
            // });
            history.push(`/order/checkout`);
        }
    };
    //添加购物车
    addCart = async () => {
        const {buyNum, selectedSku} = this.state;
        await request('/product/add-cart', {
            method: 'POST',
            data: {
                productSkuId: selectedSku?.id,
                num: buyNum
            },
        });
    };
    //价格计算
    computePrice = async (selectedAttrIds: any) => {
        let attrIdsStr = '';
        Object.keys(selectedAttrIds).forEach((key) => {
            attrIdsStr += `&attrIds=${selectedAttrIds[key]}`;
        });
        const {match: {params: {productId}}} = this.props;
        const response = await request(`/product/sku?productId=${productId}${attrIdsStr}`);
        return response.data;
    };

    onSelect = (selected: boolean, attr: skuAttr) => {
        const {skuTagList, selectedAttrIds} = this.state;
        const newSelectedAttrIds = {...selectedAttrIds};
        skuTagList.forEach((item) => {
            if (attr.skuTagId === item.id) {
                selected ? (newSelectedAttrIds[item.id] = attr.id)
                    : delete (newSelectedAttrIds[item.id]);
            }
        });
        if (skuTagList.length === Object.keys(newSelectedAttrIds).length) {
            this.computePrice(newSelectedAttrIds).then((result) => {
                this.setState({selectedSku: result.skuDetail});
            });
        }
        this.setState({selectedAttrIds: newSelectedAttrIds});
    };

    toggleSpec = (popupStatus: popupStatus) => {
        this.setState({
            popupStatus
        });
    };
    toggleCollect = () => {
        const {match: {params: {productId}}} = this.props;
        request(`/product/user-collect?productId=${productId}&isCollect=${!this.state.isCollect}`).then(() => {
            this.setState((state) => ({
                isCollect: !state.isCollect
            }));
        }).catch(() => {
            Toast.fail('请求失败')
        });
    };

    componentDidMount() {
        const {match: {params: {productId}}} = this.props;
        console.log("productId");
        console.log(productId);
        request(`/product/detail`).then((result) => {
            const {data: {isCollect, productDetail, skuTagList}} = result;
            this.setState({
                isCollect: isCollect,
                productDetail: productDetail,
                skuTagList
            })
        }).catch(() => {
            Toast.fail('请求失败')
        });
    }

    render() {
        const {history, dispatch} = this.props;
        const {productDetail, skuTagList, buyNum, selectedSku, selectedAttrIds, popupStatus} = this.state;
        return (
            <div className={styles.container}>
                {
                    popupStatus !== 'hidden' &&
                    <div className={styles.shadow} onClick={() => {
                        this.toggleSpec('hidden');
                    }}/>
                }
                <div className={styles.main}>
                    <Nav onLeftClick={() => {
                        history.goBack();
                    }}/>
                    <img src={bgImg} alt="" className={styles.bgImg}/>
                    <div className={styles.content}>
                        <div className={styles.summary}>
                            <div className={styles.goodsTitle}>
                                {productDetail?.name}
                            </div>
                            <div className={styles.priceSale}>
                                <b style={{
                                    fontSize: '16px'
                                }}>¥{productDetail?.price}</b>
                                <span>已售{productDetail?.sales}</span>
                            </div>
                        </div>
                        <br/>
                        <div className={styles.middle}>
                            <div style={{
                                paddingBottom: '8px',
                                display: 'flex',
                                justifyContent: 'space-between'
                            }}>
                                <span>运费</span>
                                <span>¥{productDetail?.freight}</span>
                            </div>
                            <div style={{
                                paddingTop: '8px',
                                borderTop: '1px solid #F9F9F9',
                                display: 'flex',
                                justifyContent: 'space-between'
                            }}>
                                <span>已选</span>
                                <span>{selectedSku?.skuFullName}</span>
                            </div>
                        </div>
                        <div className={styles.detail}>
                            <div className={styles.detailTitle}>
                                图文详情
                            </div>
                            <div className={styles.detailContent}>
                                <img
                                    src="https://img.alicdn.com/imgextra/i4/2200780288642/O1CN01KhKDQM2Di5L1rjJXd_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                                <img
                                    src="https://img.alicdn.com/imgextra/i1/2200780288642/O1CN01hEMG9v2Di5Kz3afNn_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                                <img
                                    src="https://img.alicdn.com/imgextra/i3/2200780288642/O1CN01LWbEch2Di5KtDrLKa_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                                <img
                                    src="https://img.alicdn.com/imgextra/i2/2200780288642/O1CN01S6cCdF2Di5L2YAv33_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                                <img
                                    src="https://img.alicdn.com/imgextra/i4/2200780288642/O1CN010ncpiC2Di5Kz3bwMa_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                                <img
                                    src="https://img.alicdn.com/imgextra/i2/2200780288642/O1CN01FtMB4i2Di5L0cqCyx_!!2200780288642.jpg"
                                    alt="" width={"100%"}/>
                            </div>
                        </div>
                    </div>
                </div>

                {
                    this.state.popupStatus !== 'hidden' &&
                    <Spec
                        skuTagList={skuTagList}
                        productDetail={productDetail}
                        onSelect={this.onSelect}
                        onEnsure={this.onEnsure}
                        buyNum={buyNum}
                        selectedSku={selectedSku}
                        selectedAttrIds={selectedAttrIds}
                        stepperChange={this.stepperChange}
                    />
                }
                <div className={styles.bottom}>
                    <div style={{
                        textAlign: 'center',
                        width: '56px',
                        borderRight: '1px solid #F4F4F4',
                        boxSizing: 'border-box'
                    }} onClick={this.toggleCollect}>
                        <i className={this.state.isCollect ? "iconfont icon-heart-fill" : "iconfont icon-heart"}
                           style={{
                               fontSize: '30px',
                               position: 'relative',
                           }}/>
                        <div style={{fontSize: '10px'}}>收藏</div>
                    </div>
                    <div style={{
                        textAlign: 'center',
                        width: '60px',
                        borderRight: '1px solid #F4F4F4',
                        boxSizing: 'border-box'
                    }} onClick={() => {

                        dispatch({
                            type: 'changeTab',
                            payload: 'cart'
                        });
                        history.push('/')
                    }}>
                        <i className={"iconfont icon-carryout"} style={{
                            fontSize: '30px',
                        }}/>
                        <div style={{fontSize: '10px'}}>购物车</div>
                    </div>


                    <button style={{
                        border: 'none',
                        backgroundColor: '#EBEBF3',
                        color: 'black',
                        height: '100%',
                        fontSize: '16px',
                        padding: '0 15px',
                        flex: 1,
                    }} onClick={() => {
                        this.toggleSpec('addCart');
                    }}>加入购物车
                    </button>

                    <button style={{
                        border: 'none',
                        backgroundColor: '#302F34',
                        color: 'white',
                        height: '100%',
                        fontSize: '16px',
                        padding: '0 15px',
                        flex: 1,
                    }} onClick={() => {
                        this.toggleSpec('buyNow');
                    }}>立即购买
                    </button>

                </div>
            </div>

        );
    }
}

export default connect((state: Props) => ({}), (dispatch: Dispatch) => ({
    dispatch
}))(withRouter(Index))
